package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.NearUserVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.intercepror.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 查询今日佳人：和当前用户相似度最高的一个推荐用户数据
     *   1、查询推荐用户：条件（toUserId:当前用户的id）
     *   2、查询之后获取RecommentUser对象（userId和score）
     *   3、查询用户信息
     */
    public TodayBest todayBest() {
        //1、获取当前用户id，推荐查询的条件
        Long toUserId = UserHolder.getUserId();
        //2、根据toUserId调用API查询推荐数据
        RecommendUser user = recommendUserApi.queryWitchMaxScore(toUserId);
        //3、如果没有推荐数据（模拟一个假的）
        if(user == null) {
            user = new RecommendUser();
            user.setUserId(99l);
            user.setToUserId(toUserId);
            user.setScore(95d);
        }
        //4、获取RecommentUser中的userId
        Long userId = user.getUserId();
        //5、查询推荐用户的信息
        UserInfo userInfo = userInfoApi.findById(userId);
        //6、构造返回值
        TodayBest vo = TodayBest.init(userInfo, user);
        return vo;
    }

    //查询首页推荐的用户列表
    public PageResult recommendation(Integer page, Integer pagesize) {
        //1、获取当前用户id，推荐查询的条件
        Long toUserId = UserHolder.getUserId();
        //2、调用API查询当前页的数据列表 --List<RecommendUser>
        List<RecommendUser> list = recommendUserApi.queryRecommendUserList(toUserId,page,pagesize);
        //3、判断集合数据是否为空，构造默认假数据
        if(list == null || list.isEmpty()) {
            list = defaultList();
        }
        //4、将List<RecommendUser>转化成List<TodayBest>
        List<TodayBest> vos = new ArrayList<>();

        for (RecommendUser user : list) {
            Long userId = user.getUserId(); //72.84。。
            UserInfo info = userInfoApi.findById(userId);
            TodayBest vo = TodayBest.init(info, user);
            vos.add(vo);
        }
        //5、构造返回
        return new PageResult(page,pagesize,0l,vos);
    }

    private List<RecommendUser> defaultList() {
        List<RecommendUser> list = new ArrayList<>();
        //构造默认推荐数据，企业中按照项目经理要求
        for (int i = 1; i <= 10; i++) {
            RecommendUser ru = new RecommendUser();
            ru.setUserId((long) i); //模拟推荐的用户id
            ru.setScore(95D); //模拟推荐的评分
            list.add(ru);
        }
        return list;
    }

    @DubboReference
    private VisitorsApi visitorsApi;

    //查询佳人详情
    public TodayBest personalInfo(Long userId) {
        //a:完成业务逻辑
        //1、查询用户的用户信息
        UserInfo userInfo = userInfoApi.findById(userId);
        //2、查询推荐用户数据（获取缘分值）
        Long toUserId = UserHolder.getUserId();
        RecommendUser user = recommendUserApi.queryByUserId(userId,toUserId);
        //b：保存来访记录,当前用户，查看张三
        Visitors visitors = new Visitors();
        visitors.setUserId(userId);
        visitors.setVisitorUserId(UserHolder.getUserId());
        visitors.setFrom("首页");
        visitors.setScore(user.getScore());
        visitors.setDate(System.currentTimeMillis());
        String visitDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        visitors.setVisitDate(visitDate);
        visitorsApi.save(visitors);
        //c:
        //3、构造返回的vo对象
        return TodayBest.init(userInfo,user);
    }

    //查看陌生人问题
    public String strangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId); //根据userId查询
        return question==null?"你喜欢java吗":question.getTxt();
    }


    //回复陌生人问题---向对方发送一条系统消息
    public void reply(Long userId, String reply) {
        //构建Map集合，将数据设置到map集合中
        Map map = new HashMap();
        map.put("userId",UserHolder.getUserId()); //发送人的id
        map.put("huanXinId","hx"+UserHolder.getUserId());  //发送人的环信id
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        map.put("nickname",userInfo.getNickname()); //发送人的昵称
        //陌生人问题
        String questions = strangerQuestions(userId);
        map.put("strangerQuestion",questions);
        map.put("reply",reply);
        //发布的消息JSON字符串
        String message = JSON.toJSONString(map);
        //发布消息
        huanXinTemplate.sendMsg("hx"+userId,message);//环信的账号，发布的消息JSON字符串
    }

    @DubboReference
    private UserLocationApi userLocationApi;

    /**
     * 查询附近的人
     * @param gender
     * @param distance 距离
     */
    public List<NearUserVo> search(String gender, String distance) {
        Long userId = UserHolder.getUserId();
        //1、调用API查询，附近人的id集合,包含自己的id  --List<userId>
        List<Long> list = userLocationApi.searchNear(userId,distance);
        //list -- 所有附近人的id
        Map<Long, UserInfo> map = userInfoApi.findByIds(list); //所有的附近人的信息
        //2、一个userId，构建一个NearUserVo
        List<NearUserVo> vos = new ArrayList<>();
        for (Long id : list) {
            if(userId == id) {
                continue; //跳出本次执行下一次
            }
            //获取附近人的用户信息
            UserInfo info = map.get(id);
            if(!StringUtils.isEmpty(gender)) {  //根据性别筛选
                if(!gender.equals(info.getGender())){ //性别和查询的用户行不一致
                    continue;
                }
            }
            NearUserVo vo = NearUserVo.init(info);
            vos.add(vo);
        }
        return vos;
    }
}
